package me.roger.zen.model;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import me.roger.zen.data.ZenThreadData;
import me.roger.zen.utils.ZenURLConnection;
import me.roger.zen.utils.ZenURLConnection.ZenOnResponseListener;
import me.roger.zen.utils.ZenUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.annotation.SuppressLint;
import android.util.Log;

public class ZenSearchModel extends ZenBaseModel {
	public static final String DidFinishedLoad = "ZenSearchDidFinishedLoad";
	public static final String DidFailedLoad = "ZenSearchDidFailedLoad";
	private static final String ZenSearchURL = "http://my.hupu.com/search?q=%s&type=topic&page=%d&fid=%s&sortby=datedesc";
	private String mFid;
	private String mQuery;
	private int mPage;
	private boolean isCancelled;
	private boolean clearFirst;

	private ZenURLConnection mConnection;
	public ArrayList<ZenThreadData> threads;

	private int ZenItemSubjectIndex = 0;
	private int ZenItemAuthorIndex = 2;
	private int ZenItemDateIndex = 3;
	private int ZenItemReplyIndex = 4;

	public ZenSearchModel(String fid) {
		mFid = fid;
		threads = new ArrayList<ZenThreadData>();
	}

	private boolean contains(ZenThreadData data) {
		for (ZenThreadData thread : threads) {
			if (data.tid.equals(thread.tid)) {
				return true;
			}
		}
		return false;
	}

	private void parser(String response, boolean clearFlag) {
		if(response == null) {
			send(ZenSearchModel.DidFailedLoad);
			return;
		}
		
		try {

			Document doc = Jsoup.parse(response);
			Elements eles = doc.select("tbody tr");

			if (eles != null) {
				if (clearFlag) {
					threads.clear();
				}
				for (int i = 0; i < eles.size(); i++) {
					Element element = eles.get(i);
					Elements attrs = element.select("td");
					if (attrs != null) {
						ZenThreadData thread = new ZenThreadData();
						thread.lights = "0";
						thread.fid = mFid;
						for (int j = 0; j < attrs.size(); j++) {
							Element td = attrs.get(j);
							if (j == ZenItemSubjectIndex) {
								Element a = td.select("a").first();
								if (a != null) {
									String url = a.attr("href");
									String tid = ZenUtils.sub(".com/", ".html",
											url);
									thread.tid = tid;
								}
								thread.subject = td.text();
							} else if (j == ZenItemReplyIndex) {
								thread.replies = td.text();

							} else if (j == ZenItemAuthorIndex) {
								thread.author = td.text();
							} else if (j == ZenItemDateIndex) {
								thread.postdate = td.text();
							}
						}
						if (thread != null && thread.tid != null && !contains(thread)) {
							threads.add(thread);
						}

					}
				}
				send(ZenSearchModel.DidFinishedLoad);
				return;
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
				
		
		send(ZenSearchModel.DidFailedLoad);
	}

	@SuppressLint("DefaultLocale")
	private void load(String query, int page)
			throws UnsupportedEncodingException {
		isCancelled = false;
		if (mConnection != null) {
			mConnection.cancel();
		}
		String url = String.format(ZenSearchURL,
				URLEncoder.encode(query, "gbk"), page, mFid);
		mConnection = new ZenURLConnection(url);
		mConnection.setReadCharsetName("gb2312");
		mConnection.setOnResponseListener(new ZenOnResponseListener() {

			@Override
			public void OnResponse(String response) {
				if (response == null) {
					send(ZenSearchModel.DidFailedLoad);
					return;
				}
				if (!isCancelled) {
					parser(response, clearFirst);
				}
			}

			@Override
			public void OnError(String msg) {
				Log.d("Zen", msg);
				send(ZenSearchModel.DidFailedLoad);
			}
		});
		mConnection.startAsychronous();
	}

	public void cancel() {
		if (mConnection != null) {
			mConnection.cancel();
		}
		isCancelled = true;
	}

	public void search(String query) {
		try {
			if (query == null) {
				send(ZenSearchModel.DidFailedLoad);
				return;
			}
			mQuery = query;
			clearFirst = true;
			mPage = 1;
			load(query, mPage);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void loadMore() {
		try {
			if (mQuery == null) {
				send(ZenSearchModel.DidFailedLoad);
				return;
			}
			clearFirst = false;
			mPage++;
			load(mQuery, mPage);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
